package guowenlong.golf.ui.friend.myfriends;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.ViewHolder;
import android.widget.LinearLayout;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.OnClick;
import cc.solart.turbo.OnItemClickListener;
import cc.solart.wave.WaveSideBarView;
import guowenlong.golf.R;
import guowenlong.golf.base.BaseFragment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;

/**
 * des   : 描述 author: Administrator email : guowenlong20000@gmail.com time  : 2017年02月13日 上午 12:46.
 */

public class MyFriendFragment extends BaseFragment {

  @BindView(R.id.ll_myfriend_add)
  LinearLayout llMyfriendAdd;
  @BindView(R.id.recycler_view)
  RecyclerView mRecyclerView;
  @BindView(R.id.side_view)
  WaveSideBarView mSideBarView;
  public static List<ContactsInfo> list = new ArrayList<>();
  private ContansAdapter adapter;
  private ArrayList<ContactsInfo> templists = new ArrayList<>();
  private String[] strs = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
      "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

  @Override
  public int getLayoutId() {
    return R.layout.fragment_myfriend;
  }

  @Override
  public void initView() {
    mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    final PinnedHeaderDecoration decoration = new PinnedHeaderDecoration();
    decoration.registerTypePinnedHeader(1, new PinnedHeaderDecoration.PinnedHeaderCreator() {
      @Override
      public boolean create(RecyclerView parent, int adapterPosition) {
        return true;
      }
    });
    mRecyclerView.addItemDecoration(decoration);
    if (ContextCompat
        .checkSelfPermission(getActivity(), android.Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(getActivity(),
          new String[]{android.Manifest.permission.READ_CONTACTS},
          1);
    } else {
      getContans();
    }
    adapter = new ContansAdapter(getActivity(), templists);
    mRecyclerView.setAdapter(adapter);
    mSideBarView.setOnTouchLetterChangeListener(new WaveSideBarView.OnTouchLetterChangeListener() {
      @Override
      public void onLetterChange(String letter) {
        int pos = adapter.getLetterPosition(letter);

        if (pos != -1) {
          mRecyclerView.scrollToPosition(pos);
          LinearLayoutManager mLayoutManager =
              (LinearLayoutManager) mRecyclerView.getLayoutManager();
          mLayoutManager.scrollToPositionWithOffset(pos, 0);
        }
      }
    });
    adapter.addOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(ViewHolder vh, int position) {
        if (templists.get(position).getType() != 1) {
          startActivity(new Intent(getActivity(),MyFriendInfoActivity.class));
        }
      }
    });
  }

  private void getContans() {
    try {
      Uri contactUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
      Cursor cursor = getActivity().getContentResolver().query(contactUri,
          new String[]{"display_name", "sort_key", "contact_id", "data1"},
          null, null, "sort_key");
      String contactName;
      String contactNumber;
      String contactSortKey;
      int contactId;
      while (cursor.moveToNext()) {
        contactName = cursor
            .getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        contactNumber = cursor
            .getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        contactId = cursor
            .getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
        contactSortKey = getSortkey(cursor.getString(1));
        ContactsInfo contactsInfo = new ContactsInfo(contactName, contactNumber, contactSortKey,
            contactId, 0);
        contactsInfo
            .setSortKey(HanyuPinyinHelper.getFirstLetters(contactsInfo.getName().substring(0, 1),
                HanyuPinyinCaseType.UPPERCASE));
        if (contactName != null) {
          list.add(contactsInfo);
        }
      }
      cursor.close();//使用完后一定要将cursor关闭，不然会造成内存泄露等问题

    } catch (Exception e) {
      e.printStackTrace();
    }
    templists = new ArrayList<>();
    for (int i = 0; i < strs.length; i++) {
      for (int j = 0; j < list.size(); j++) {
        if (list.get(j).getSortKey() != null && list.get(j).getSortKey().equals(strs[i])) {
          templists.add(new ContactsInfo(strs[i], 1));
          break;
        }
      }
    }
    templists.addAll(list);
    Collections.sort(templists, new LetterComparator());
  }

  private static String getSortkey(String sortKeyString) {
    String key = sortKeyString.substring(0, 1).toUpperCase();
    if (key.matches("[A-Z]")) {
      return key;
    } else {
      return "#";   //获取sort key的首个字符，如果是英文字母就直接返回，否则返回#。
    }
  }

  @Override
  public void initData(Bundle savedInstanceState) {

  }

  @OnClick(R.id.ll_myfriend_add)
  public void onClick() {
    startActivity(new Intent(getActivity(),AddFriendsActivity.class));
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions,
      int[] grantResults) {
    if (requestCode == 1) {
      if (grantResults.length > 0
          && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        getContans();
        initView();
      } else {
        Toast.makeText(mContext, "如果不给与权限部分功能将影响您的使用", Toast.LENGTH_SHORT).show();
      }
    }
  }
}